package com.ydd.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisUtil {
    @Autowired
    private RedisTemplate<String, Object> stringRedisTemplate;
//    private final StringRedisTemplate stringRedisTemplate;

//    @Autowired
//    public RedisUtil(StringRedisTemplate stringRedisTemplate) {
//        this.stringRedisTemplate = stringRedisTemplate;
//    }

    /***
     * 添加并设置过期时间
     * @param key
     * @param value
     * @param expire
     */
    public void addWithExpire(String key, String value, int expire) {
        // 设置键值对
        stringRedisTemplate.opsForValue().set(key, value);

        // 设置过期时间
        if (expire > 0) {
            stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    public boolean delete(String key) {
        boolean delete = stringRedisTemplate.delete(key);
        return delete;
    }

    public Long increment(String userKey, Integer delta) {
        return stringRedisTemplate.opsForValue().increment(userKey, delta);
    }

    public void set(String key, String val, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, val, time, timeUnit);
    }

    public Boolean hasKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    public String getZipNo() {
        String key = "serialNumber:zipNo";

        Long no = stringRedisTemplate.opsForValue().increment(key);
        if (no == null) {
            no = 1L;
            stringRedisTemplate.opsForValue().set(key, String.valueOf(no), 365L, TimeUnit.DAYS);
        }
        return String.valueOf(no);
    }

    /**
     * 根据键获取对应的值。
     *
     * @param key 从Redis中获取值的键，类型为String。
     * @return 如果找到对应的键，则返回其值，类型为String。如果没有找到，则返回null。
     */
    public String get(String key) {
        // 通过stringRedisTemplate操作Redis获取key对应的value
        return stringRedisTemplate.opsForValue().get(key).toString();
    }

}